package site.wanjiahao.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import site.wanjiahao.constant.FileConstant;
import site.wanjiahao.entity.FileEntity;
import site.wanjiahao.service.FileService;
import site.wanjiahao.utils.FileUtils;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static java.nio.charset.StandardCharsets.UTF_8;

@Controller
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 文件上传请求， 并且限制上传空文件, 保证后续流程正确
     */
    @ResponseBody
    @PostMapping("/upload")
    public String upload(MultipartFile file)  {
        try {
            return fileService.upload(file);
        } catch (Exception e) {
            log.error("文件上传接口出现异常, {}", e.getMessage());
        }
        return FileConstant.ERROR;
    }

    @GetMapping("/fetch/{uuid}")
    public void fetch(@PathVariable String uuid, HttpServletResponse response) {
        try {
            FileEntity fileEntity = fileService.getAbsoluteFilePathByUUID(uuid);
            String originName = fileEntity.getOriginName();
            String type = String.valueOf(new MimetypesFileTypeMap().getContentType(originName));
            // 设置contentType，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type",type);
            // 解决中文乱码
            originName = new String(originName.getBytes(UTF_8),
                    StandardCharsets.ISO_8859_1);
            // 以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + originName);
            FileUtils.download(fileEntity.getFilePath(), response);
        } catch (FileNotFoundException fileNotFoundException) {
            log.debug("上传文件未找到, {}", fileNotFoundException.getMessage());
            // 返回错误响应
            response.setStatus(HttpServletResponse.SC_GONE);
        } catch (Exception e) {
            log.debug("服务器未知异常, {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_GONE);
        }
    }

    @ResponseBody
    @GetMapping("/fetch_metadata/{uuid}")
    public FileEntity fetchMetadata(@PathVariable String uuid) {
        // 文件找不到，直接返回空对象, 无需异常处理
        return fileService.findByUUID(uuid);
    }

}
